package com.softeem.hbsm_video.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.hbsm_video.entity.Category;
import com.softeem.hbsm_video.entity.User;
import com.softeem.hbsm_video.entity.Video;
import com.softeem.hbsm_video.service.CategoryService;
import com.softeem.hbsm_video.utils.QiniuOssUtils;
import com.softeem.hbsm_video.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.UUID;

/**
 * @author ZhouYu
 * @version 1.0
 * 视频频道业务接口
 */
@RequestMapping("/category")
@RestController
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public R list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer limit){
        List<Category> list = categoryService.list(new Page<Category>(page, limit));

        //查询总记录数
        long count = categoryService.count();
        return R.ok("查询成功").setData(list).setCount(count);
    }


    /**
     * 添加
     * @param category
     * @return
     */
    @Transactional
    @PostMapping("/add")
    public R add(@RequestBody Category category) {
        if (category.getName() == null || category.getName().isEmpty()) {
            return R.fail("分类名不能为空");
        }

        boolean saveResult = categoryService.save(category);
        return saveResult ? R.ok("添加成功") : R.fail("添加失败");
    }


    /**
     * 文件上传
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    public R upload(MultipartFile file){
        try {
            //对本次上传的文件生成随机key(UUID)
            String key = UUID.randomUUID().toString();
            //获取文件输入流
            InputStream inputStream = file.getInputStream();
            //创建OSS工具类对象
            QiniuOssUtils utils = new QiniuOssUtils();
            //将文件流上传到七牛OSS
            String url = utils.upload(inputStream, key);
            return R.ok("上传成功").setData(url);
        } catch (Exception e) {
            return R.fail("上传失败");
        }
    }


    /**
     * 修改
     * @param category
     * @return
     */
    @PostMapping("/update")
    public R update(@RequestBody Category category){
        boolean result = categoryService.updateById(category);
        return result ? R.ok("修改成功") : R.fail("修改失败");
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public R delete(Integer id){
        boolean result = categoryService.removeById(id);
        return result ? R.ok("删除成功") : R.fail("删除失败");
    }
}
